//
// Created by Scave on 2025/8/25.
//

#include "SceneManager.h"

NS_RIDER_BEGIN

    SceneManager::SceneManager() {
    }

    SceneManager::~SceneManager() {
        SAFE_DELETE_PTR(current_scene_);
        for (auto* scene: scene_list_) {
            SAFE_DELETE_PTR(scene);
        }
        scene_list_.clear();
    }

    Scene* SceneManager::CreateScene() {
        Scene* scene = new Scene();
        scene_list_.push_back(scene);
        return scene;
    }

    Scene* SceneManager::CreateScene(const Name& name) {
        Scene* scene = new Scene(name);
        scene_list_.push_back(scene);
        return scene;
    }

    Scene* SceneManager::GetCurrentScene() {
        return current_scene_;
    }

    Scene* SceneManager::FindScene(const Name& name) {
        for (auto* scene: scene_list_) {
            if (scene->GetName() == name) {
                return scene;
            }
        }
        return nullptr;
    }

    Scene* SceneManager::operator[](const Name& name) {
        return FindScene(name);
    }

    void SceneManager::LoadScene(Scene* scene) {
        if (current_scene_) {
            current_scene_->OnUnLoad();
        }
        current_scene_ = scene;
        renderer_->SetScene(scene);
        current_scene_->OnLoad();
    }

    void SceneManager::LoadScene(const Name& name) {
        auto* scene = FindScene(name);
        if (scene != nullptr) {
            LoadScene(scene);
        }
    }

    void SceneManager::SetRenderConfig(RenderConfig config) {
        this->renderer_ = MAKE_SMART_PTR<SceneRenderer>(config);
    }

    void SceneManager::Flush() {
        current_scene_->Update();
        renderer_->Render();
    }

NS_RIDER_END
